package com.rabbit.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zjw
 * @date 2022/2/8 10:32
 */
public class RequestUtil {

    /**
     * 获取请求参数
     *
     * @param joinPoint 切点
     * @return String 请求参数
     */
    public static String getRequestParams(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        Map<String, String[]> map = request.getParameterMap();
        if (!CollectionUtils.isEmpty(map)) {
            return JSONObject.toJSONString(map);
        } else {
            Object[] args = joinPoint.getArgs();
            if (args != null && args.length > 0) {
                return argsToString(joinPoint.getArgs());
            }
        }
        return "";
    }

    /**
     * argsToString
     */
    private static String argsToString(Object[] args) {
        List<Object> argsList = Arrays.asList(args);
        return JSON.toJSONString(argsList);
    }

}
